package com.vuej.core;

import com.vuej.entity.VueFile;
import com.vuej.entity.VueFileScript;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 默认VueFileParser的实现，正则表达式提取xml内容，提取成template、script、style
 */
public class DefaultVueFileParser implements VueFileParser {

    //匹配template、script、style标签的正则表达式：

    protected static final Pattern PATTERN_TEMPLATE = Pattern.compile("<template[^>]*>([\\s\\S]*)</template>", Pattern.CASE_INSENSITIVE);

    protected static final Pattern PATTERN_SCRIPT = Pattern.compile("<script[^>]*>([\\s\\S]*)</script>", Pattern.CASE_INSENSITIVE);

    protected static final Pattern PATTERN_STYLE = Pattern.compile("<style[^>]*>([\\s\\S]*)</style>", Pattern.CASE_INSENSITIVE);


    @Override
    public VueFile parse(String content) {
        VueFile vueFile = new VueFile();
        Matcher templateMatcher = PATTERN_TEMPLATE.matcher(content);
        if (templateMatcher.find()) {
            vueFile.setTemplate(templateMatcher.group(1).trim());
        }
        Matcher scriptMatcher = PATTERN_SCRIPT.matcher(content);
        if (scriptMatcher.find()) {
            String scriptAll = scriptMatcher.group(1);
            if(!scriptAll.isEmpty()){
                int i = scriptAll.indexOf("{");
                int j = scriptAll.lastIndexOf("}");
                int k = scriptAll.indexOf("export");
                if(i == -1 || j == -1 || k == -1){
                    throw new IllegalStateException("script 标签不匹配固定格式 export default {...}");
                }
                VueFileScript script = new VueFileScript();
                vueFile.setScript(script);


                script.setExports(scriptAll.substring(i + 1, j).trim());
                script.setBefore(scriptAll.substring(0,k).trim());
            }
        }
        Matcher styleMatcher = PATTERN_STYLE.matcher(content);
        if (styleMatcher.find()) {
            vueFile.setStyle(styleMatcher.group(1).trim());
        }

        return vueFile;
    }
}
